package com.initialize.core.jwt;

import com.initialize.core.jwt.cookie.RsaUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @program: star-blockchain
 * @description: token常量
 * @author: Mr.Jane
 * @create: 2019-10-09 15:39
 **/
@Configuration
@Data
@Slf4j
public class JwtProperties {

    public static final String TEST_TOKEN = "11111";
    /**
     * 密钥
     */
    @Value("${auth.jwt.secret}")
    private String secret;

    /**
     * 公钥地址
     */
    @Value("${auth.jwt.pubKeyPath}")
    private String pubKeyPath;

    /**
     * 私钥地址
     */
    @Value("${auth.jwt.priKeyPath}")
    private String priKeyPath;

    /**
     * token过期时间
     */
    @Value("${auth.jwt.expire}")
    private int expire;
    /**
     * 临时token过期时间
     */
    @Value("${auth.jwt.temporaryTokenExpire}")
    private int temporaryTokenExpire;
    /**
     * 公钥
     */
    private PublicKey publicKey;

    /**
     * 私钥
     */
    private PrivateKey privateKey;

    /**
     * cookie名字
     */
    @Value("${auth.jwt.cookieName}")
    private String cookieName;


    /**
     * cookie生命周期
     */
    @Value("${auth.jwt.cookieMaxAge}")
    private Integer cookieMaxAge;


    /**
     * @PostConstruct :在构造方法执行之后执行该方法
     */
    @PostConstruct
    public void init() {
        try {
            log.info("pubKeyPath  {}", pubKeyPath);
            log.error("加载rsa公钥和私钥");
            File pubKey = new File(pubKeyPath);
            File priKey = new File(priKeyPath);
            if (!pubKey.exists() || !priKey.exists()) {
                log.error("秘钥不存在, 生成rsa公钥和私钥  ");
                RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
            }
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
        } catch (Exception e) {
            log.error("初始化公钥和私钥失败！", e);
            throw new RuntimeException();
        }
    }
}
